package cn.edu.tsinghua.training.demo;

import java.util.List;
import java.util.Set;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

import cn.edu.tsinghua.training.demo.entity.Article;
import cn.edu.tsinghua.training.demo.entity.Channel;

public class App {
	
	public static void main(String[] args) {
		
		Configuration configuration = new Configuration().configure();
		ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
		SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
		
		Session session = sessionFactory.openSession();
		Transaction transaction = session.beginTransaction();
		
//		Channel channel = new Channel(null, "测试");
//		session.save(channel);
//		transaction.commit();
		
//		Channel channel = (Channel) session.get(Channel.class, 2);
//		Article article = new Article(null, "测试二", channel);
//		session.save(article);
//		transaction.commit();
		
//		String queryString = "select c.name, a.title from Channel c, Article a where c.id=a.channel";
//		Query query = session.createQuery(queryString);
//		List<Object[]> list = query.list();
//		for (Object[] objects : list) {
//			System.out.println(objects[0] + "," + objects[1]);
//		}
		
//		String queryString = "from Channel";
//		Query query = session.createQuery(queryString);
//		List<Channel> channels = query.list();
//		for (Channel channel : channels) {
//			Set<Article> articles = channel.getArticles();
//			for (Article article : articles) {
//				System.out.println(article.getChannel().getName() + ", " + article.getTitle());
//			}
//		}
		
		Channel channel = (Channel) session.get(Channel.class, 1);
		channel.setName("test");
		session.update(channel);
		transaction.commit();
		
		session.close();
		sessionFactory.close();
		
		System.out.println("done.");
	}
}
